
import { resetRouter } from "@/router";
import { store } from "@/stores";
import AuthAPI from "@/api/auth";
import UserAPI from "@/api/user";
export const useUserStore = defineStore("user", () => {
  const user = ref({
    roles: [],
    perms: [],
  });
  const token = ref('')
  const openEcho = ref(false)
  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  const login = (loginData) => {
    return new Promise((resolve, reject) => {
      AuthAPI.loginToken(loginData).then(({ data }) => {
        token.value = `${data.token_type} ${data.token}`
        resolve(data);
      }).catch((error) => {
        reject(error);
      });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo () {
    return new Promise((resolve, reject) => {
      UserAPI.user()
        .then(({ data }) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          Object.assign(user.value, { ...data }, {
            roles: ["ADMIN"],
            perms: [
              "sys:menu:delete",
              "sys:dept:edit",
              "sys:dict_type:add",
              "sys:dict:edit",
              "sys:dict:delete",
              "sys:dict_type:edit",
              "sys:menu:add",
              "sys:user:add",
              "sys:role:edit",
              "sys:dept:delete",
              "sys:user:password_reset",
              "sys:user:edit",
              "sys:user:delete",
              "sys:dept:add",
              "sys:role:delete",
              "sys:dict_type:delete",
              "sys:menu:edit",
              "sys:dict:add",
              "sys:role:add",
            ],
            avatar: "",
          });
          openEcho.value = true
          resolve(user.value);
        })
        .catch((error) => {
          reject(error);
        });
      // const data = {
      //   userId: 2,
      //   username: "admin",
      //   nickname: "系统管理员",
      //   avatar:
      //     "https://oss.youlai.tech/youlai-boot/2023/05/16/811270ef31f548af9cffc026dfc3777b.gif",

      // };
      // Object.assign(user.value, { ...data });
      // resolve(data);
    });
  }

  // user logout
  function logout () {
    return new Promise((resolve, reject) => {
      AuthAPI.logoutToken().then(() => {
        openEcho.value = false
        token.value = ''
        location.reload(); // 清空路由
        resolve();
      }).catch((error) => {
        reject(error);
      })
    });
  }

  // remove token
  function resetToken () {
    console.log("resetToken");
    return new Promise((resolve) => {
      // localStorage.setItem(TOKEN_KEY, "");
      // resetRouter();
      resolve();
    });
  }
  const setToken = (str) => {
    token.value = str
  }

  return {
    openEcho,
    token,
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
    setToken
  };
}, {
  persist: {
    storage: localStorage,
    pick: ['token'],
  },
});

// 非setup
export function useUserStoreHook () {
  return useUserStore(store);
}
